#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
#  Project: Kelindo - Unsupervised Music Organizer  
#  Author: Nicola Bicocchi <nicola.bicocchi@gmail.com>, Nicolo' Torreggiani <nicolo.torreggiani@gmail.com>, Gianluca Puglia <gianluca.puglia@gmail.com>, Matteo Senardi <pualien@gmail.com>
#  Copyright: 2013 Nicola Bicocchi, Nicolo' Torreggiani, Gianluca Puglia, Matteo Senardi
#  License: GPL-2+
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
# 
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
# 
# On Debian GNU/Linux systems, the full text of the GNU General Public License
# can be found in the file /usr/share/common-licenses/GPL-2.
##

import gtk
import os.path

import kelindo.const

class Details(gtk.Dialog):
    
    def __init__(self, path, albums):
        super(Details, self).__init__(
            title = 'Select albums...',
            parent = None,
            flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                    gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
                    
        self.path = path
        self.albums = albums
        self.move_files = False
        self.show_all = False
        
        self.liststore = gtk.ListStore(bool, gtk.gdk.Pixbuf, str, str, str, str)
        self.liststore.set_sort_column_id(2, gtk.SORT_ASCENDING)
        self.treeView = gtk.TreeView()
        self.treeView.set_rules_hint(True)
        self.treeView.get_selection().set_mode(gtk.SELECTION_NONE)  
        self.treeView.set_model(self.liststore)
        
        rendererToggle = gtk.CellRendererToggle()
        column = gtk.TreeViewColumn('Include', rendererToggle, active=0)
        column.set_sort_column_id(0)
        column.set_resizable(True)
        rendererToggle.connect('toggled', self.__include_update)
        self.treeView.append_column(column)
        
        rendererPixbuf = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn('Confidence', rendererPixbuf, pixbuf=1)
        column.set_sort_column_id(1)
        column.set_resizable(True)
        self.treeView.append_column(column)
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Artist', rendererText, text=2)
        column.set_sort_column_id(2)
        column.set_resizable(True)
        self.treeView.append_column(column)   
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Album', rendererText, text=3)
        column.set_sort_column_id(3)
        column.set_resizable(True)
        self.treeView.append_column(column)   
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Medium', rendererText, text=4)
        column.set_sort_column_id(4)
        column.set_resizable(True)
        self.treeView.append_column(column)  
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Original Folder', rendererText, text=5)
        column.set_sort_column_id(5)
        column.set_resizable(True)
        self.treeView.append_column(column)
        self.treeView.show()
        
        sw = gtk.ScrolledWindow()
        sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.add(self.treeView)
        sw.show()
        
        self.set_size_request(800, 600)
        self.vbox.add(sw)
        
        self.box = gtk.HBox(False, 0)
        self.vbox.pack_start(self.box, False, True, 5)
        self.box.show()

        self.combobox_show = gtk.combo_box_new_text()
        self.combobox_show.connect('changed', self.__match_all_update)
        self.combobox_show.append_text('Show matches')
        self.combobox_show.append_text('Show all')
        self.combobox_show.set_sensitive(True)
        self.combobox_show.set_active(0)
        self.combobox_show.show()
        self.box.pack_start(self.combobox_show, False, True, 5)

        self.combobox_copy = gtk.combo_box_new_text()
        self.combobox_copy.append_text('Copy files')
        self.combobox_copy.append_text('Move files')
        self.combobox_copy.set_sensitive(True)
        self.combobox_copy.set_active(0)
        self.combobox_copy.show()
        self.box.pack_start(self.combobox_copy, False, True, 5)
        
        self.combobox_consolidate = gtk.combo_box_new_text()
        for fmt in ['As Source', 'FLAC', 'MP3', 'OGG']:
            self.combobox_consolidate.append_text(fmt)
        self.combobox_consolidate.set_sensitive(True)
        self.combobox_consolidate.set_active(0)
        self.combobox_consolidate.show()
        self.box.pack_start(self.combobox_consolidate, False, True, 5)

        self.combobox_dst = gtk.combo_box_new_text()
        self.combobox_dst.connect('changed', self.__dst_folder_update)        
        self.combobox_dst.append_text(kelindo.const.OUTPUTDIR)
        self.combobox_dst.append_text('Choose folder..')        
        self.combobox_dst.set_active(0)
        self.combobox_dst.set_size_request(250,0)
        self.combobox_dst.show()
        self.box.pack_end(self.combobox_dst, False, False, 5)
        
        label = gtk.Label("Destination Folder: ")
        self.box.pack_end(label, False, False, 0)
        label.show()    
        
        self.__list_update()
        return
        
    def __match_all_update(self, widget):
        model = widget.get_model()
        index = widget.get_active()
        self.show_all = False
        if model[index][0] == 'Show all':
            self.show_all = True
        self.__list_update()
        return

    def __dst_folder_update(self, widget):
        model = widget.get_model()
        index = widget.get_active()
        if index:
            if model[index][0] == 'Choose folder..':
                dialog = gtk.FileChooserDialog("Choose Folder",None,gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN, gtk.RESPONSE_OK))
                dialog.set_default_response(gtk.RESPONSE_OK)
                response = dialog.run()
                if response == gtk.RESPONSE_OK:
                    self.dir_output = dialog.get_filename()
                    widget.insert_text(0, self.dir_output)
                widget.set_active(0)
                dialog.destroy()
        return
        
    def __include_update(self, widget, path):
        model = self.treeView.get_model()
        t_iter = model.get_iter(path)
        for album in self.albums:
            if os.path.relpath(album.dir, self.path) == model.get_value(t_iter, 5):
                v = not model.get_value(t_iter, 0)
                model.set_value(t_iter, 0, v)
                album.finalize = v
                break
        self.__list_update()
        return
        
    def __list_update(self):
        self.liststore.clear()
        for album in self.albums:            
            if self.show_all == False and album.status != 'MATCH':
                continue
            
            if album.status == 'MATCH':          
                artist_name = album.best_candidate[0]['albumauthors']
                album_name = album.best_candidate[0]['albumtitle'] 
                album_medium = 'CD%s' % (album.best_candidate[0]['trackmedium'],)
                if album.distance > 0.5:
                    pixbuf = gtk.gdk.pixbuf_new_from_file(
                        os.path.join(kelindo.const.IMAGEDIR, 'hicolor/16x16/green.png'))
                else:
                    pixbuf = gtk.gdk.pixbuf_new_from_file(
                        os.path.join(kelindo.const.IMAGEDIR, 'hicolor/16x16/yellow.png')) 
            elif album.status == 'NO_MATCH':
                artist_name = '' 
                album_name = ''
                album_medium = ''
                pixbuf = gtk.gdk.pixbuf_new_from_file(
                    os.path.join(kelindo.const.IMAGEDIR, 'hicolor/16x16/red.png'))
            else:
                artist_name = '' 
                album_name = ''
                album_medium = ''
                pixbuf = gtk.gdk.pixbuf_new_from_file(
                    os.path.join(kelindo.const.IMAGEDIR, 'hicolor/16x16/broken.png'))
            
            self.liststore.append((album.finalize, 
                              pixbuf, 
                              artist_name, 
                              album_name,
                              album_medium,
                              os.path.relpath(album.dir, self.path)))  
        return